<?php
Authenticate::requireAccounting();
$db = Db::getInstance();
$db->autocommit(false);
try {
	$invoices = array();//Invoice::getInvoices();
	$curDate = new DateTime();
	$query = "SELECT *,YEARWEEK(createTime) FROM Invoice";
	$mode = isset($_GET['mode'])? $_GET['mode']: 'daily';
	if($mode=='weekly'){
		$query .= " WHERE (YEARWEEK(createTime) = YEARWEEK(CURRENT_DATE))";
	}
	else if($mode=='monthly'){
		$query .= " WHERE (MONTH(createTime) = MONTH(CURRENT_DATE))";
	}
	else if($mode=='yearly'){
		$query .= " WHERE (YEAR(createTime) = YEAR(CURRENT_DATE))";
	}
	else {
		$query .= " WHERE (DATE(createTime) = DATE(CURRENT_DATE))";
	}
	$query .= " ORDER BY createTime DESC";
	$result = $db->query($query);
	$invoices = array();
	$invoicesPay = array();
	while($row = $result->fetch_assoc()){
		$row['account'] = Account::instance()->getOne($row['accountId']);
		$row['package'] = Package::instance()->getOne($row['packageId']);
		if($row['status']==Invoice::STATUS_PAY){
			$invoicesPay[] = $row;
			continue;
		}
		$invoices[] = $row;
	}
	//if(!$invoices) { View::display('message', array('head'=> 'invoice', 'message'=> 'ไม่พบ invoice นี้')); }
	View::display('accounting/invoice', array('invoices'=> $invoices, 'invoicesPay'=> $invoicesPay));
} catch(Exception $ex) {
	echo $ex;
}